package com.WOWTradeNews.services;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.WOWTradeNews.Utils;

import org.apache.http.HttpConnection;
import org.json.JSONArray;
import org.json.JSONObject;


import android.util.Log;

import com.WOWTradeNews.DataBase.ConstValues;
import com.WOWTradeNews.DataBase.News;

/**
 * 广告类
 * @author zhaosdfa
 *
 */
public class AD {
	private static final String AD_PATH = "http://www.mi-great.com.tw/wow/json/json_gu.asp?theme=7";
	
	/**
	 * 获取广告列表
	 * @return
	 * @throws Exception 
	 */
	public static List<News> getAdList() throws Exception {
		List<News> res = new ArrayList<News>();
		
		URL url = new URL(AD_PATH);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		
		if(conn.getResponseCode() == 200) {
			InputStream inputStream = conn.getInputStream();
			res = paressJson(inputStream);
		}
		
		return res;
	}

	private static List<News> paressJson(InputStream inputStream) throws Exception{
		byte[] data = Utils.readInputStream(inputStream);
		String json = new String(data);
		List<News> res = new ArrayList<News>();
		
		//Log.d("zhaosdfa", json);
		//{"iid":4,"title":"廣告4","alinks":"http://www.msn.cn","img":"http://mi-great.com.tw/wow//adimg/201309043_02.jpg"}
		
		JSONArray jsonArray = new JSONArray(json);
		
		for(int i=0; i<jsonArray.length(); i++) {
			JSONObject obj = jsonArray.getJSONObject(i);
			int iid = obj.getInt("iid");
			String title = obj.getString("title");
			String alinks = obj.getString("alinks");
			String img = obj.getString("img");
			
			//Log.d("json", "iid:"+iid + ",title:" + title + ",alinks:" + alinks + ",img:" + img );
			
			News news = new News();
			news.flag = 1;
			news.setIid(String.valueOf(iid));
			//news.setAdIid(iid);
			//news.setAdTitle(title);
			//news.setAdPath(alinks);
			//news.setAdImgPath(img);
			news.setSubject(title);
			news.setTxt1Url(alinks);
			news.setImg1Url(img);
			
			if(img != null && !img.equals("")) {
				news.setImg(Utils.getUrlBitmapBonus(img));
			}
			
			news.setNewsType(ConstValues.NEWS_TYPE_AD);
			
			res.add(news);
		}
		
		return res;
	}
	
}
